package com.hgkj.common.async;

import com.hgkj.common.core.utils.SpringContextUtils;
import com.hgkj.common.async.template.AsyncResultTask;
import com.hgkj.common.async.template.AsyncTask;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * 异步任务管理器
 */
public class AsyncManager {

    private static volatile AsyncManager instance;

    /**
     * 线程池实例（通过Spring上下文获取）
     */
    private final ThreadPoolTaskExecutor taskExecutor;

    /**
     * 私有构造函数（防止外部实例化）
     * 从Spring上下文获取线程池 Bean
     */
    private AsyncManager() {
        // 防止通过反射破坏单例
        if (instance != null) {
            throw new IllegalStateException("单例实例已存在，禁止重复创建");
        }
        taskExecutor = SpringContextUtils.getBean(ThreadPoolTaskExecutor.class);
    }

    /**
     * 双重检查
     */
    public static AsyncManager getInstance(){
        if (Objects.isNull(instance)) {
            synchronized (AsyncManager.class) {
                if (Objects.isNull(instance)) {
                    instance = new AsyncManager();
                }
            }
        }
        return instance;
    }

    /**
     * 创建并执行无返回值任务
     * @param task 无返回值任务
     */
    public void execute(AsyncTask task) {
        taskExecutor.submit(task::execute);
    }

    /**
     * 创建并执行有返回值任务
     */
    public <T> CompletableFuture<T> execute(AsyncResultTask<T> task) {
        return CompletableFuture.supplyAsync(task::execute, taskExecutor);
    }
}
